<template>
	<view class="game-container" :style="{backgroundImage: 'url(' + bgImage + ')'}">
		<!-- 顶部游戏信息栏 -->
		<view class="game-header">
			<view class="level-info">
				<text class="level-text">第 {{currentLevel}} 关</text>
				<text class="progress-text">{{correctCount}}/{{totalIdioms}}</text>
			</view>
			<view class="score-info">
				<image class="score-icon" src="/static/icons/star.png"></image>
				<text class="score-text">{{totalScore}}</text>
			</view>
		</view>

		<!-- 游戏主区域 -->
		<view class="game-main">
			<!-- 上一个成语 -->
			<view class="previous-idiom" v-if="previousIdiom">
				<text class="idiom-text">{{previousIdiom}}</text>
			</view>

			<!-- 当前成语卡片 -->
			<view class="idiom-card">
				<text class="idiom-char" v-for="(char, index) in currentIdiomChars" :key="index">
					{{char}}
				</text>
			</view>
			<view class="idiom-description">
				<view class="yin">{{yin}}</view>
				<view class="idiom-explan">{{description}}</view>
			</view>

			<!-- 输入区域 -->
			<view class="input-area">
				<input v-model="userInput" placeholder="请输入接龙成语" placeholder-class="placeholder" @confirm="checkAnswer"
					focus />
				<button class="submit-btn" @click="checkAnswer">提交</button>
			</view>

			<!-- 提示信息 -->
			<view class="hint-area" v-if="hintMessage">
				<text :class="['hint-text', hintClass]">{{hintMessage}}</text>
			</view>
		</view>

		<!-- 游戏结果弹窗 -->
		<view class="result-modal" v-if="showResult">
			<view class="result-content">
				<text class="result-title">恭喜通关！</text>
				<text class="result-desc">您已完成第 {{currentLevel}} 关</text>

				<view class="result-stats">
					<view class="stat-item">
						<text class="stat-value">{{correctCount}}</text>
						<text class="stat-label">正确成语</text>
					</view>
					<view class="stat-item">
						<text class="stat-value">{{totalScore}}</text>
						<text class="stat-label">获得积分</text>
					</view>
				</view>

				<button class="next-level-btn" @click="upLevel">下一关</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				currentLevel: 1,
				correctCount: 0,
				totalIdioms: 2, // 第一关5个成语
				totalScore: 0,
				previousIdiom: '',
				currentIdiom: '一帆风顺',
				yin: 'yi fang feng shun',
				description: '指做事没阻碍，很顺利',
				userInput: '',
				hintMessage: '',
				hintClass: '',
				showResult: false,
				bgImage: '/static/bg/game-bg2.png',
			}
		},
		computed: {
			currentIdiomChars() {
				return this.currentIdiom.split('')
			}
		},
		onLoad() {
			this.loadGameData()
			this.getRandomData()

		},
		methods: {
			async loadGameData() {
				try {
					const token = uni.getStorageSync('token')
					const res = await uni.request({
						url: 'http://localhost:8003/api/v1/game/index',
						method: 'GET',
						header: {
							'Authorization': 'Bearer ' + token
						}
					})

					if (res.statusCode === 200 && res.data.code === 200) {
						let result = res.data.data;
						console.log("game index", result)
						this.currentLevel = result.level
						this.totalScore = result.score
						this.startLevel()
					} else {
						throw new Error(res.data.message || '加载游戏数据失败')
					}
				} catch (error) {
					console.error('加载游戏数据失败:', error)
					uni.showToast({
						title: error.message,
						icon: 'none'
					})
				}
			},

			async getRandomData() {
				try {
					const token = uni.getStorageSync('token')
					const res = await uni.request({
						url: 'http://localhost:8003/api/v1/game/getRandomOne',
						method: 'GET',
						header: {
							'Authorization': 'Bearer ' + token
						}
					})

					if (res.statusCode === 200 && res.data.code === 200) {
						let result = res.data.data;
						this.currentIdiom = result.name
						this.yin = result.yin
						this.description = result.description
					} else {
						throw new Error(res.data.message || '加载游戏数据失败')
					}
				} catch (error) {
					console.error('加载游戏数据失败:', error)
					uni.showToast({
						title: error.message,
						icon: 'none'
					})
				}
			},


			async checkAnswer() {
				if (!this.userInput) {
					this.showHint('请输入成语', 'error')
					return
				}
				if (this.userInput.length !== 4) {
					this.showHint('成语应为4个字', 'error')
					return
				}
				// 检查接龙规则
				const lastChar = this.currentIdiom.slice(-1)
				const firstChar = this.userInput[0]
				if (lastChar !== firstChar) {
					this.showHint(`请以"${lastChar}"开头`, 'error')
					return
				}

				try {
					const token = uni.getStorageSync('token')
					const res = await uni.request({
						url: 'http://localhost:8003/api/v1/game/checkExist?name=' + this.userInput,
						method: 'GET',
						header: {
							'Authorization': 'Bearer ' + token
						}
					})

					if (res.statusCode === 200 && res.data.code === 200) {
						let result = res.data.data;
						if (result) {
							this.showHint('回答正确！', 'success')
							this.nextSuccess()
							// 检查是否过关
							if (this.correctCount >= this.totalIdioms) {
								this.showResult = true
								//this.startLevel()
							}
						} else {
							this.showHint('成语不存在', 'error')
						}
					} else {
						throw new Error(res.data.message || '加载游戏数据失败')
					}
				} catch (error) {
					console.error('加载游戏数据失败:', error)
					uni.showToast({
						title: error.message,
						icon: 'none'
					})
				}
			},

			async upLevel() {
				try {
					const token = uni.getStorageSync('token')
					const res = await uni.request({
						url: 'http://localhost:8003/api/v1/game/upLevel',
						method: 'POST',
						data: {},
						header: {
							'Content-Type': 'application/json',
							'Authorization': 'Bearer ' + token
						}
					})
					if (res.statusCode === 200 && res.data.code === 200) {
						this.currentLevel++
						this.startLevel()
					} else {
						throw new Error(res.data.message || '升级失败')
					}
				} catch (error) {
					console.error('加载游戏数据失败:', error)
				}
			},

			showHint(message, type) {
				this.hintMessage = message
				this.hintClass = type

				clearTimeout(this.hintTimer)
				this.hintTimer = setTimeout(() => {
					this.hintMessage = ''
				}, 2000)
			},


			startLevel() {
				this.correctCount = 0
				this.totalIdioms = 2 + this.currentLevel // 每关增加一个成语
				this.previousIdiom = ''
				this.userInput = ''
				this.hintMessage = ''
				this.showResult = false
			},

			nextSuccess() {
				this.getRandomData();
				this.correctCount++
				this.totalScore += 10 * this.currentLevel
				this.previousIdiom = this.currentIdiom
				this.currentIdiom = this.userInput
				this.userInput = ''
			}
		}
	}
</script>

<style lang="scss">
	page {
		height: 100%;
		overflow: hidden;
	}

	.game-container {
		height: 100vh;
		width: 100vw;
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;
		display: flex;
		flex-direction: column;
		padding: 30rpx;
		box-sizing: border-box;
		position: relative;
		overflow: hidden;

		&::before {
			content: '';
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: rgba(255, 255, 255, 0.85);
			z-index: 0;
		}
	}

	.game-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 40rpx;
		position: relative;
		z-index: 1;

		.level-info {
			background-color: rgba(58, 123, 213, 0.1);
			border-radius: 40rpx;
			padding: 12rpx 24rpx;
			display: flex;
			align-items: center;

			.level-text {
				font-size: 28rpx;
				color: #3a7bd5;
				font-weight: bold;
				margin-right: 15rpx;
			}

			.progress-text {
				font-size: 26rpx;
				color: #666;
			}
		}

		.score-info {
			display: flex;
			align-items: center;

			.score-icon {
				width: 36rpx;
				height: 36rpx;
				margin-right: 10rpx;
			}

			.score-text {
				font-size: 32rpx;
				color: #ff9900;
				font-weight: bold;
			}
		}
	}

	.game-main {
		flex: 1;
		display: flex;
		flex-direction: column;
		position: relative;
		z-index: 1;
	}

	.previous-idiom {
		background-color: rgba(255, 255, 255, 0.7);
		border-radius: 16rpx;
		padding: 20rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

		.idiom-text {
			font-size: 36rpx;
			color: #666;
			text-align: center;
			display: block;
		}
	}

	.idiom-card {
		background-color: #fff;
		border-radius: 24rpx;
		padding: 40rpx;
		margin-bottom: 40rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
		display: flex;
		justify-content: space-around;

		.idiom-char {
			font-size: 60rpx;
			color: #333;
			font-weight: bold;
			text-align: center;
			flex: 1;
		}
	}

	.idiom-description {
		background-color: #fff;
		border-radius: 24rpx;
		padding: 20rpx;
		margin-bottom: 40rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);

		.yin {
			padding: 10rpx;
			margin-bottom: 10rpx;
		}

		.idiom-explan {
			padding: 10rpx;
			margin-bottom: 10rpx;
		}
	}

	.input-area {
		display: flex;
		margin-bottom: 30rpx;

		input {
			flex: 1;
			height: 80rpx;
			background-color: #fff;
			border-radius: 40rpx 0 0 40rpx;
			padding: 0 30rpx;
			font-size: 32rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

			.placeholder {
				color: #bbb;
				font-size: 32rpx;
			}
		}

		.submit-btn {
			width: 160rpx;
			height: 80rpx;
			line-height: 80rpx;
			background: linear-gradient(to right, #3a7bd5, #00d2ff);
			color: #fff;
			border-radius: 0 40rpx 40rpx 0;
			font-size: 32rpx;
			box-shadow: 0 4rpx 12rpx rgba(58, 123, 213, 0.3);

			&::after {
				border: none;
			}
		}
	}

	.hint-area {
		text-align: center;
		margin-top: 20rpx;

		.hint-text {
			font-size: 28rpx;
			padding: 10rpx 20rpx;
			border-radius: 40rpx;
			display: inline-block;

			&.success {
				background-color: rgba(82, 196, 26, 0.1);
				color: #52c41a;
			}

			&.error {
				background-color: rgba(255, 77, 79, 0.1);
				color: #ff4d4f;
			}
		}
	}

	.result-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 10;

		.result-content {
			background-color: #fff;
			border-radius: 24rpx;
			padding: 50rpx;
			width: 80%;
			text-align: center;
			box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);

			.result-title {
				font-size: 40rpx;
				color: #3a7bd5;
				font-weight: bold;
				display: block;
				margin-bottom: 20rpx;
			}

			.result-desc {
				font-size: 30rpx;
				color: #666;
				display: block;
				margin-bottom: 40rpx;
			}

			.result-stats {
				display: flex;
				justify-content: space-around;
				margin-bottom: 50rpx;

				.stat-item {
					display: flex;
					flex-direction: column;

					.stat-value {
						font-size: 48rpx;
						color: #3a7bd5;
						font-weight: bold;
						margin-bottom: 10rpx;
					}

					.stat-label {
						font-size: 26rpx;
						color: #999;
					}
				}
			}

			.next-level-btn {
				background: linear-gradient(to right, #3a7bd5, #00d2ff);
				color: #fff;
				border-radius: 50rpx;
				height: 90rpx;
				line-height: 90rpx;
				font-size: 34rpx;
				font-weight: bold;
				box-shadow: 0 8rpx 20rpx rgba(58, 123, 213, 0.3);

				&::after {
					border: none;
				}
			}
		}
	}
</style>